package com.shop.autoshop.controller;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.shop.autoshop.pay.alipay.AlipayNotifyBean;
import com.shop.autoshop.pay.alipay.AlipayService;
import com.shop.autoshop.pay.wxpay.WxpayService;
import com.shop.autoshop.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @version:0.0.1
 * @author: Lianyutao
 * @create: 2020-10-20 10:13
 * @description:
 **/

@Slf4j
@RestController
@RequestMapping("pay")
public class PayNotifyController {

    @Resource
    private AlipayService alipayService;

    @Resource
    private WxpayService wxpayService;

    @Resource
    private PayService payService;

    /**
     * 支付宝支付通知
     *
     * @return OrderCouponUseVO
     */
    @PostMapping("notify/alipay")
    public String notifyAlipay(HttpServletRequest request, AlipayNotifyBean alipayNotifyBean) {
        log.info("支付回调成功");
        log.info("收到支付宝通知: {}", JSON.toJSONString(alipayNotifyBean));
        // 验签
        if (alipayService.checkSign(request)) {
            log.error("checkSign 成功");
            // 收到支付宝异步通知,返回success,支付宝不再通知
            return payService.notifyAlipay(alipayNotifyBean);
        }
        log.error("checkSign失败");
        return "failure";
    }


    /**
     * 微信支付通知
     *
     * @return OrderCouponUseVO
     */
    @PostMapping("notify/wxpay")
    public String notifyWxpay(@RequestBody String xmlData){
        log.info("微信支付回调成功");
        log.info("收到微信通知: {}", xmlData);
        final WxPayOrderNotifyResult notifyResult = wxpayService.notify(xmlData);
        if (notifyResult != null) {
            boolean flag = payService.notifyWxpay(notifyResult);
            if (flag) {
                return WxPayNotifyResponse.success("成功");
            }
        }
        return WxPayNotifyResponse.fail("失败");
    }

}
